from wxpyview.ui.core.BaseUIGenerator import *

class MainUIGenerator(BaseUIGenerator):
    def __init__(self):
        BaseUIGenerator.__init__(self)
        
        self.meta_widget_tree = MetaWidgetTree()
        
    def _releaseMemory(self):
        del self.dom_tree
        
    def parse(self, resource_path):
        BaseUIGenerator.parse(self, resource_path)
        
        self.dom_tree = DOM()
        self.dom_tree.create(resource_path)
        self._createMetaWidgets()
        
        print self.dom_tree.getType()
        
        self._releaseMemory()

    # generate MetaWidgetTree from DOM.
    def _createMetaWidgets(self):
        self.meta_widget = None
        dom_tree_head = self.dom_tree.getRootNode()
        meta_widget_tree_head = self.meta_widget_tree.getRootMetaWidget()
        self._aCreateMetaWidgets(dom_tree_head, meta_widget_tree_head)
        
    def _aCreateMetaWidgets(self, parent_dom, parent_meta_widget):
        child_dom_nodes = parent_dom.childNodes
        
        for dom_node in child_dom_nodes:
            # create meta-widget tree
            if dom_node.nodeType == dom_node.ELEMENT_NODE:
                # when node is wx:dataProvider
                if dom_node.nodeName == "wx:dataProvider":
                    data_provider = InternalDataProvider(dom_node)
                    parent_meta_widget.setDataProvider(data_provider)
                    continue
                
                self.meta_widget = MetaWidgetEntry()
                self.meta_widget.setDOM(dom_node)
                self.meta_widget_tree.setLink(parent_meta_widget, self.meta_widget)

                # for external data provider
                if dom_node.hasAttribute("dataProvider"):
                    external_data_provider = ExternalDataProvider(dom_node)
                    self.meta_widget.setDataProvider(external_data_provider)
                
                # add name of DOM object to the index for event binding.
                # indexing MetaWidget by name
                name = dom_node.getAttribute("name")
                self.meta_widget_tree.setNameIndexForMetaWidget(self.meta_widget, name)
       
            self._aCreateMetaWidgets(dom_node, self.meta_widget)
    
    # generate real widgets by traversing MetaWidgetTree
    def createRealWidgets(self):
        BaseUIGenerator.createRealWidgets(self)

        head_meta_widget = self.meta_widget_tree.getRootMetaWidget()

        if head_meta_widget == None:
            raise "INVALID OR UNINITIALIZATION OF DOM" 

        self.top_widget_object = self.widget_generator.generate(head_meta_widget)
        self._aCreateRealWidgets(head_meta_widget)
        return self.top_widget_object

    def getMetaWidgetTree(self):
        return self.meta_widget_tree